package com.ruoyi.web.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.liangshi.domain.*;
import com.ruoyi.liangshi.service.*;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author LiuJin
 * @Date: Create in 2023-11-21 13:31
 * @Description: this class is 菜品耗时分析类
 * 该类会生成 bi_bs_ksc、bi_bs_ksc_hour、bi_bs_ksc_day、bi_bs_ksc_month表的数据
 */
@Component
public class BiBsKscTask {

    @Autowired
    private IBsOrderService bsOrderService;

    @Autowired
    private IBizKcKscService bizKcKscService;

    @Autowired
    private IBiBsKscService biBsKscService;

    @Autowired
    private IArchItemService archItemService;

    @Autowired
    private IGdArchShiftService gdArchShiftService;

    @Autowired
    private IBiBsKscHourService biBsKscHourService;

    @Autowired
    private IBiBsKscDayService biBsKscDayService;


    @Autowired
    private IBiBsKscMonthService biBsKscMonthService;


    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 菜品类型
     */
    private List<String> archTypeList = Arrays.asList("A", "B", "C");

    /**
     * 下单类型,1:主动下单,2:被迫下单
     */
    private List<String> timeOutTypeList = Arrays.asList("1", "2");

    @Value("${arch-item.excluds}")
    private String archItemExcluds;
    /**
     * 将数据同步至bi_bs_ksc表中
     */
//    @Scheduled(cron = "0/60 * * * * ?")
    public void syncBiBsKscData() {
        List<String> excludeItemIds = Arrays.asList(archItemExcluds.split(","));
        //查询已结算但是未同步bi表的订单
        List<BsOrder> orderList = bsOrderService.lambdaQuery()
                .isNotNull(BsOrder::getSettleTime)
                .eq(BsOrder::getIsBiSync, "1")
                .list();
        List<BiBsKsc> biBsKscList = new ArrayList<>();
        for (BsOrder bsOrder : orderList) {
            //查询kitchen_flag=3订单详情
            List<BizKcKsc> kscList = bizKcKscService.lambdaQuery()
                    .eq(BizKcKsc::getBsId, bsOrder.getId())
                    .eq(BizKcKsc::getKitchenFlg,"3")
                    .notIn(BizKcKsc::getItemId,excludeItemIds)
                    .list();
            for (BizKcKsc bizKcKsc : kscList) {
                BiBsKsc biBsKsc = new BiBsKsc();
                biBsKsc.setBsId(bsOrder.getId());
                biBsKsc.setBsDate(DatePattern.NORM_DATE_FORMAT.format(bsOrder.getOpenTime()));
                biBsKsc.setBsHour(String.valueOf(bsOrder.getOpenTime().getHours()));
                biBsKsc.setShift(bsOrder.getOpenShiftId().toString());
                biBsKsc.setItemId(bizKcKsc.getItemId());
                ArchItem archItem = archItemService.getById(biBsKsc.getItemId());
                //如果查询的菜品为空，则结束本次循环
                if (ObjectUtil.isNull(archItem)) {
                    continue;
                }
                biBsKsc.setItemType(archItem.getAtchType());
                if (DateUtil.between(bsOrder.getOpenTime(), bizKcKsc.getCreateTime(), DateUnit.MINUTE) < 5l) {
                    biBsKsc.setTimeOutType("1");
                } else {
                    biBsKsc.setTimeOutType("2");
                }
                biBsKsc.setShopId(bizKcKsc.getCreateShopId());
                //使用开台时间和传菜完成时间计算总耗时
                long consumeTime = DateUtil.between(bizKcKsc.getCallUpTime(), bizKcKsc.getServeFinishTime(), DateUnit.SECOND);
                //使用开台时间和切配完成时间计算出切配耗时
                long cookTime = DateUtil.between(bizKcKsc.getCallUpTime(), bizKcKsc.getCookFinishTime(), DateUnit.SECOND);
                //使用切配完成时间和传菜完成时间计算出传菜耗时
                long serveTime = DateUtil.between( bizKcKsc.getCookFinishTime(),bizKcKsc.getServeFinishTime(), DateUnit.SECOND);
                biBsKsc.setConsumeTime(new BigDecimal(consumeTime));
                biBsKsc.setCookTime(new BigDecimal(cookTime));
                biBsKsc.setServeTime(new BigDecimal(serveTime));
                biBsKscList.add(biBsKsc);
            }
            bsOrder.setIsBiSync("2");
            bsOrderService.updateById(bsOrder);
        }
        if (biBsKscList.size() > 0) {
            biBsKscService.saveBatch(biBsKscList);
        }
    }

    /**
     * 基础内容：按班次（2种）、菜品类型（3种）、下单类型（2种）进行同步
     * 最少的同步记录条数为2*3*2=12条。
     * 如果为按小时同步，则一小时的记录条数为12条，一天24小时的记录条数为288条
     * 按天同步，则一天记录条数为12
     * 按月同步，则一个月的记录条数为12
     */


    /**
     * 10分钟同步一次小时数据
     */
//    @Scheduled(cron = "0/60 * * * * ?")
    public void syncBiBsKscHourData() {
        List<BiBsKscHour> biBsKscHourList = new ArrayList<>();
        List<GdArchShift> list = gdArchShiftService.list();
//        List<SysDept> sysDepts = sysDeptService.selectDeptList(null);
//        for (SysDept sysDept : sysDepts) {
            //遍历班次信息
            for (GdArchShift gdArchShift : list) {
                //遍历菜品类型
                for (String archType : archTypeList) {
                    //遍历下单类型
                    for (String timeOutType : timeOutTypeList) {
                        Date currentDate = new Date();
                        currentDate.setMonth(10);
                        for (int j = 1; j <= 30; j++) {
                            currentDate.setDate(j);
                            for (int i = 0; i < 24; i++) {
                                currentDate.setHours(i);
                                //先删再加
                                biBsKscHourService.lambdaUpdate()
                                        .eq(BiBsKscHour::getShift, gdArchShift.getId().toString())
                                        .eq(BiBsKscHour::getItemType, archType)
                                        .eq(BiBsKscHour::getTimeOutType, timeOutType)
                                        //查询昨天数据
                                        .eq(BiBsKscHour::getBsDate, DatePattern.NORM_DATE_FORMAT.format(currentDate))
                                        //查询某个小时的数据
                                        .eq(BiBsKscHour::getBsHour, i)
                                        .eq(BiBsKscHour::getShopId,59948l)
                                        .remove();
                                //根据班次信息、菜品类型、下单类型、小时、时间为昨天查询数据
                                List<BiBsKsc> bsKscList = biBsKscService.lambdaQuery()
                                        .eq(BiBsKsc::getShift, gdArchShift.getId().toString())
                                        .eq(BiBsKsc::getItemType, archType)
                                        .eq(BiBsKsc::getTimeOutType, timeOutType)
                                        //查询昨天数据
                                        .eq(BiBsKsc::getBsDate, DatePattern.NORM_DATE_FORMAT.format(currentDate))
                                        //查询某个小时的数据
                                        .eq(BiBsKsc::getBsHour, i)
                                        .eq(BiBsKsc::getShopId,59948l)
                                        .list();
//                                if (ObjectUtil.isEmpty(bsKscList)) {
//                                    continue;
//                                }
                                //总消耗时长
                                BigDecimal totalTime = BigDecimal.ZERO;
                                BigDecimal totalCookTime = BigDecimal.ZERO;
                                BigDecimal totalServeTime = BigDecimal.ZERO;
                                BigDecimal totalDishes = BigDecimal.ZERO;
                                for (BiBsKsc biBsKsc : bsKscList) {
                                    totalTime = totalTime.add(biBsKsc.getConsumeTime());
                                    totalCookTime = totalCookTime.add(biBsKsc.getCookTime());
                                    totalServeTime = totalServeTime.add(biBsKsc.getServeTime());
                                    totalDishes = totalDishes.add(BigDecimal.ONE);
                                }
                                //构建数据集合、插入数据库
                                BiBsKscHour biBsKscHour = new BiBsKscHour();
                                biBsKscHour.setShopId(59948l);
                                biBsKscHour.setDishesCount(totalDishes);
                                biBsKscHour.setBsDate(DatePattern.NORM_DATE_FORMAT.format(currentDate));
                                biBsKscHour.setBsHour(currentDate.getHours());
                                biBsKscHour.setConsumeTime(totalTime);
                                biBsKscHour.setCookTime(totalCookTime);
                                biBsKscHour.setServeTime(totalServeTime);
                                biBsKscHour.setItemType(archType);
                                biBsKscHour.setTimeOutType(timeOutType);
                                biBsKscHour.setShift(String.valueOf(gdArchShift.getId()));
                                biBsKscHourList.add(biBsKscHour);
                            }
                        }
                    }
                }
            }
//        }
        if (biBsKscHourList.size() > 0) {
            biBsKscHourService.saveBatch(biBsKscHourList);
        }
    }

    /**
     * 1小时同步一次天数据
     */
//    @Scheduled(cron = "0/10 * * * * ?")
    public void syncBiBsKscDayData() {
        List<BiBsKscDay> bsKscDayList = new ArrayList<>();
        List<GdArchShift> list = gdArchShiftService.list();
        //遍历班次信息
        for (GdArchShift gdArchShift : list) {
            //遍历菜品类型
            for (String archType : archTypeList) {
                //遍历下单类型
                for (String timeOutType : timeOutTypeList) {
                    Date currentDate = new Date();
                    currentDate.setMonth(10);
                    for (int i = 1; i <=30 ; i++) {
                        currentDate.setDate(i);
                    //先删后加
                    biBsKscDayService.lambdaUpdate()
                            .eq(BiBsKscDay::getShift, gdArchShift.getId().toString())
                            .eq(BiBsKscDay::getItemType, archType)
                            .eq(BiBsKscDay::getTimeOutType, timeOutType)
                            //查询昨天数据
                            .eq(BiBsKscDay::getBsDate, DatePattern.NORM_DATE_FORMAT.format(currentDate))
                            .eq(BiBsKscDay::getBsDay, currentDate.getDate())
                            .remove();
                    //根据班次信息、菜品类型、下单类型、时间为昨天查询数据
                    List<BiBsKsc> bsKscList = biBsKscService.lambdaQuery()
                            .eq(BiBsKsc::getShift, gdArchShift.getId().toString())
                            .eq(BiBsKsc::getItemType, archType)
                            .eq(BiBsKsc::getTimeOutType, timeOutType)
                            //查询昨天数据
                            .eq(BiBsKsc::getBsDate, DatePattern.NORM_DATE_FORMAT.format(currentDate))
                            .list();
                    if (ObjectUtil.isEmpty(bsKscList)) {
                        continue;
                    }
                    if (ObjectUtil.isEmpty(bsKscList)) {
                        continue;
                    }
                    //总消耗时长
                    BigDecimal totalTime = BigDecimal.ZERO;
                    BigDecimal totalDishes=BigDecimal.ZERO;
                    for (BiBsKsc biBsKsc : bsKscList) {
                        totalTime = totalTime.add(biBsKsc.getConsumeTime());
                        totalDishes=totalDishes.add(BigDecimal.ONE);
                    }
                    //构建数据集合、插入数据库
                    BiBsKscDay biBsKscDay = new BiBsKscDay();
                    biBsKscDay.setShopId(bsKscList.get(0).getShopId());
                    biBsKscDay.setBsDate(bsKscList.get(0).getBsDate());
                    biBsKscDay.setBsDay(String.valueOf(currentDate.getDate()));
                    biBsKscDay.setDishesCount(totalDishes);
                    biBsKscDay.setConsumeTime(totalTime);
                    biBsKscDay.setItemType(archType);
                    biBsKscDay.setTimeOutType(timeOutType);
                    biBsKscDay.setShift(String.valueOf(gdArchShift.getId()));
                    bsKscDayList.add(biBsKscDay);
                }
            }
        }
        }
        if (bsKscDayList.size() > 0) {
            biBsKscDayService.saveBatch(bsKscDayList);
        }
    }

    /**
     * 1天同步一次月数据
     */
//    @Scheduled(cron = "0/10 * * * * ?")
    public void syncBiBsKscMonthData() {
        List<BiBsKscMonth> bsKscMonthList = new ArrayList<>();
        List<GdArchShift> list = gdArchShiftService.list();
        Date currentDate = new Date();
        currentDate.setMonth(10);
        //遍历班次信息
        for (GdArchShift gdArchShift : list) {
            //遍历菜品类型
            for (String archType : archTypeList) {
                //遍历下单类型
                for (String timeOutType : timeOutTypeList) {
                    //先删再加
                    biBsKscMonthService.lambdaUpdate()
                            .eq(BiBsKscMonth::getShift, gdArchShift.getId().toString())
                            .eq(BiBsKscMonth::getItemType, archType)
                            .eq(BiBsKscMonth::getTimeOutType, timeOutType)
                            //按时间格式化方式查询月份数据
                            .apply("DATE_FORMAT(bs_date,'%Y%m')=DATE_FORMAT({0},'%Y%m')", currentDate)
                            .remove();

                    //根据班次信息、菜品类型、下单类型、时间为上个月查询数据
                    List<BiBsKsc> bsKscList = biBsKscService.lambdaQuery()
                            .eq(BiBsKsc::getShift, gdArchShift.getId().toString())
                            .eq(BiBsKsc::getItemType, archType)
                            .eq(BiBsKsc::getTimeOutType, timeOutType)
                            //按时间格式化方式查询月份数据
                            .apply("DATE_FORMAT(bs_date,'%Y%m')=DATE_FORMAT({0},'%Y%m')", currentDate)
                            .list();
                    if (ObjectUtil.isEmpty(bsKscList)) {
                        continue;
                    }
                    //总消耗时长
                    BigDecimal totalTime = BigDecimal.ZERO;
                    BigDecimal totalDishes=BigDecimal.ZERO;
                    for (BiBsKsc biBsKsc : bsKscList) {
                        totalTime = totalTime.add(biBsKsc.getConsumeTime());
                        totalDishes=totalDishes.add(BigDecimal.ONE);
                    }
                    //构建数据集合、插入数据库
                    BiBsKscMonth bsKscMonth = new BiBsKscMonth();
                    bsKscMonth.setShopId(bsKscList.get(0).getShopId());
                    bsKscMonth.setBsDate(DatePattern.NORM_MONTH_FORMAT.format(currentDate));
                    bsKscMonth.setBsMonth(String.valueOf(currentDate.getMonth()));
//                    bsKscMonth.setBsMonth(String.valueOf(new Date().getMonth() + 1));
                    bsKscMonth.setDishesCount(totalDishes);
                    bsKscMonth.setConsumeTime(totalTime);
                    bsKscMonth.setItemType(archType);
                    bsKscMonth.setTimeOutType(timeOutType);
                    bsKscMonth.setShift(String.valueOf(gdArchShift.getId()));
                    bsKscMonthList.add(bsKscMonth);
                }
            }
        }
        if (bsKscMonthList.size() > 0) {
            biBsKscMonthService.saveBatch(bsKscMonthList);
        }
    }

    public static void main(String[] args) {
        Date date = new Date();
        date.setMonth(10);
        String s = DateUtil.formatDate(date);
        System.out.println(s);
    }
}
